package commands;

import user.Admin;
import user.User;
import messages.*;
import core.PluginManager;
import core.UserManager;
import event.*;
import exceptions.UserAlreadyExistsException;


/**
 * The StartPlugin command.
 * 
 * This command will handle StartPlugin messages.
 */
public class StartPluginCommand extends Command {

	
	public StartPluginCommand(Message message, User user) {
		super(message, user);
	}
	
	
	@Override
	public void execute() {
		PluginManager pluginManager = controller.getPluginManager();
		StartPluginMessage message = (StartPluginMessage) this.message;
		message.setSenderLogin(this.user.getLogin());
		
		String pluginName = message.getPluginName();
		
		PluginOperationFailedMessage.ErrorCode errorCode = null;
		
		synchronized (pluginManager) {
		
			if (!(this.user instanceof Admin)) {
				errorCode = PluginOperationFailedMessage.ErrorCode.InsufficientPermissions;
			} else if (!pluginManager.containsPlugin(pluginName)) {
				errorCode = PluginOperationFailedMessage.ErrorCode.UnknownPlugin;
			} else if (!pluginManager.startPlugin(pluginName)) {
				errorCode = PluginOperationFailedMessage.ErrorCode.OperationFailed;
			}
		}
			
		if (errorCode != null) {
			controller.firePluginOperationFailedEvent(new PluginOperationFailedEventArgs(this.user.getLogin(), 
					new PluginOperationFailedMessage(errorCode, message)));
		} else {
			controller.firePluginOperationSuccessfulEvent(new PluginOperationSuccessfulEventArgs(this.user.getLogin(), 
					new PluginOperationSuccessfulMessage(message)));
		}
	}
}
